const db = require('../db/index.js')
// 导入brcyptjs加密
const bcrypt = require('bcryptjs')
// 导入生成token包
const jwt = require('jsonwebtoken')
// 导入全局配置文件
const config = require('../config')
// 邮箱
let nodemailer = require('nodemailer');
// 注册用户的处理函数
exports.regUser = (req, res) => {
	console.log(req.user)
	const userinfo = req.body
	console.log(userinfo)
	const sqlStr = 'select * from ev_users where username=?'
	db.query(sqlStr, [userinfo.username], (err, results) => {
		if (err) {
			return res.cc(err)
		}
		if (results.length > 0) {
			return res.cc('用户名已存在！')
		}
		console.log(req.body)
		const sqlmail = 'select * from mail where mail=? and code=?'
		console.log(userinfo.mail)
		console.log(userinfo.code)
		db.query(sqlmail, [userinfo.mail,userinfo.code], function(err, results) {
			if (err) {
				return res.cc(err)
			}
			if (results.length==0) {
				return res.cc('邮箱或验证码无效！')
			}
			if (results[0].is_code!='0') {
				return res.cc('验证码无效！')
			}
			const emailId=results[0].mailId
			userinfo.password = bcrypt.hashSync(userinfo.password, 10)
			const insertSql = 'insert into ev_users set ?'
			db.query(insertSql, {
				username: userinfo.username,
				password: userinfo.password,
				emailId:emailId
			}, function(err, results) {
				if (err) {
					return res.cc(err)
				}
				if (results.affectedRows != 1) {
					return res.cc('注册失败，请稍后重试！')
				}
				res.cc('注册成功！', 0)
			})
		})
		
	})
}
exports.regUserCode = (req, res) => {
	console.log(req.user)
	console.log(req.body)
	let randomNum = Math.random().toFixed(6).slice(-6)
	const sqlmail = 'select * from mail where mail=?'
	db.query(sqlmail, req.body.mail, function(err, results) {
		if (err) {
			return res.cc(err)
		}
		if (results.length > 0) {
			return res.cc('邮箱已存在！')
		}
		console.log(results)
		const insertSql = 'insert into mail set ?'
		
		db.query(insertSql, {
			mail: req.body.mail,
			code: randomNum,
			is_code:0
		}, function(err, results) {
			if (err) {
				return res.cc(err)
			}
			if (results.affectedRows != 1) {
				return res.cc('存入验证码成功！')
			}
			let options = {
				from: ' "世界上所有的相遇都是久别重逢。" <3515722788@qq.com>',
				to: `<${req.body.mail}>`,
				bcc: '密送',
				subject: `明明早已百无禁忌，偏偏你是一百零一。${randomNum}`,
				text: `我爱宇宙，爱星星尘埃，爱孤单际遇。我爱山河湖海，爱叽喳鸟鸣，爱茵茵绿芽。我爱四季更迭，爱化冰后的叮咚小溪，爱一树簌簌下落的飘雪，然后停在你这里。您的验证码为${randomNum}`,
				// html: `<h1>hello zhy ${randomNum}</h1>`
			};
			let transporter = nodemailer.createTransport({
			    host:'smtp.qq.com',
			    port:587,
			    secure: false,
			    auth:{
			      user:'3515722788@qq.com',
			      pass:'xxx'
			    }
			  })
			transporter.sendMail(options, function(err, msg) {
				if (err) {
					console.log(err);
					res.send(err);
				} else {
					res.send('success');
					setTimeout(()=>{
						console.log('执行定时任务！')
						const updateSql='update mail set is_code=? where mail=?'
						db.query(updateSql,[1,req.body.mail],(err,results)=>{
							if (err) return console.log(err.message)
							// 行数
							// 插入则results是一个对象
							if (results.affectedRows === 1){console.log('更新数据成功')}
						})
					},300000)
				}
			})
		})
	})
	
	
}
// 登录的处理函数
exports.login = (req, res) => {
	console.log(req.user)
	console.log('登录！')
	const userinfo = req.body
	console.log(userinfo)
	const sql = 'select * from ev_users where username=?'
	db.query(sql, userinfo.username, (err, results) => {
		if (err) return res.cc(err)
		if (results.length !== 1) {
			return res.cc('登录失败！用户名不存在！')
		}
		const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
		if (!compareResult) {
			return res.cc('登录失败！密码错误！')
		}
		// 再服务端生成token的字符串
		const user = {
			...results[0],
			password: '',
			user_pic: ''
		}
		console.log(user)
		// 对用户信息进行加密，生成token字符串
		const tokenStr = jwt.sign(user, config.jwtSecretKey, {
			expiresIn: config.expiresIn
		})
		console.log('Bearer ' + tokenStr)
		// Bearer方便客户端使用
		res.send({
			status: 0,
			message: '登录成功！',
			token: 'Bearer ' + tokenStr
		})
	})
}